#!/bin/bash

# 宝塔面板NFC锁具管理系统快速部署脚本
# 使用方法：chmod +x bt-quick-deploy.sh && ./bt-quick-deploy.sh

echo "=========================================="
echo "宝塔面板 - NFC锁具管理系统快速部署脚本"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="nfc-lock-system"
PROJECT_DIR="/www/wwwroot/$PROJECT_NAME"
DB_NAME="nfc_lock_system"
DB_USER="root"

# 函数：打印彩色消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 函数：检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 未安装，请先安装 $1"
        return 1
    fi
    return 0
}

# 函数：检查服务状态
check_service() {
    if systemctl is-active --quiet $1; then
        print_message "$1 服务正在运行"
        return 0
    else
        print_error "$1 服务未运行，请启动 $1 服务"
        return 1
    fi
}

# 步骤1：环境检查
print_message "步骤1：检查部署环境..."

# 检查Java
if check_command java; then
    JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2)
    print_message "Java版本：$JAVA_VERSION"
else
    exit 1
fi

# 检查Maven
if check_command mvn; then
    MAVEN_VERSION=$(mvn -version | head -n 1 | cut -d' ' -f3)
    print_message "Maven版本：$MAVEN_VERSION"
else
    exit 1
fi

# 检查MySQL
if check_service mysql; then
    MYSQL_VERSION=$(mysql --version | cut -d' ' -f6 | cut -d',' -f1)
    print_message "MySQL版本：$MYSQL_VERSION"
else
    exit 1
fi

# 步骤2：创建项目目录
print_message "步骤2：创建项目目录..."
if [ ! -d "$PROJECT_DIR" ]; then
    mkdir -p "$PROJECT_DIR"
    print_message "项目目录已创建：$PROJECT_DIR"
else
    print_warning "项目目录已存在：$PROJECT_DIR"
fi

# 创建日志目录
mkdir -p "$PROJECT_DIR/logs"
print_message "日志目录已创建：$PROJECT_DIR/logs"

# 步骤3：数据库配置
print_message "步骤3：配置数据库..."

# 提示输入MySQL密码
echo -n "请输入MySQL root密码: "
read -s DB_PASSWORD
echo

# 测试数据库连接
if mysql -u$DB_USER -p$DB_PASSWORD -e "SELECT 1;" &> /dev/null; then
    print_message "数据库连接成功"
else
    print_error "数据库连接失败，请检查密码"
    exit 1
fi

# 创建数据库
print_message "创建数据库 $DB_NAME..."
mysql -u$DB_USER -p$DB_PASSWORD -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

# 导入数据库结构
if [ -f "db/init-database.sql" ]; then
    print_message "导入数据库结构..."
    mysql -u$DB_USER -p$DB_PASSWORD $DB_NAME < db/init-database.sql
    print_message "数据库初始化完成"
else
    print_warning "未找到数据库初始化文件，请手动导入"
fi

# 步骤4：配置文件更新
print_message "步骤4：更新配置文件..."

# 备份原配置文件
if [ -f "src/main/resources/application-prod.yml" ]; then
    cp src/main/resources/application-prod.yml src/main/resources/application-prod.yml.backup
    print_message "配置文件已备份"
fi

# 更新数据库密码
sed -i "s/password:.*/password: $DB_PASSWORD/" src/main/resources/application-prod.yml
print_message "数据库密码已更新"

# 步骤5：编译和打包
print_message "步骤5：编译和打包项目..."

# 清理之前的构建
mvn clean

# 编译项目
print_message "编译项目..."
if mvn compile; then
    print_message "项目编译成功"
else
    print_error "项目编译失败"
    exit 1
fi

# 打包项目
print_message "打包项目..."
if mvn package -DskipTests -Pprod; then
    print_message "项目打包成功"
else
    print_error "项目打包失败"
    exit 1
fi

# 步骤6：部署项目
print_message "步骤6：部署项目到 $PROJECT_DIR..."

# 复制文件
cp -r src "$PROJECT_DIR/"
cp pom.xml "$PROJECT_DIR/"
cp -r target "$PROJECT_DIR/"
cp bt-panel-start.sh "$PROJECT_DIR/"
cp "宝塔面板部署指南.md" "$PROJECT_DIR/"

# 设置权限
chown -R www:www "$PROJECT_DIR"
chmod +x "$PROJECT_DIR/bt-panel-start.sh"

print_message "项目文件部署完成"

# 步骤7：启动服务
print_message "步骤7：启动服务..."

cd "$PROJECT_DIR"

# 检查端口占用
if netstat -tlnp | grep :8080 &> /dev/null; then
    print_warning "端口8080已被占用，请先停止占用该端口的服务"
    netstat -tlnp | grep :8080
    echo -n "是否强制停止占用端口的进程？(y/N): "
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        PID=$(netstat -tlnp | grep :8080 | awk '{print $7}' | cut -d'/' -f1)
        kill -9 $PID
        print_message "已停止进程 $PID"
    else
        print_error "请手动停止占用端口8080的服务后重新运行"
        exit 1
    fi
fi

# 启动应用
print_message "启动NFC锁具管理系统..."
nohup mvn spring-boot:run -Dspring-boot.run.profiles=prod > logs/startup.log 2>&1 &

# 等待启动
print_message "等待应用启动..."
sleep 10

# 检查启动状态
if netstat -tlnp | grep :8080 &> /dev/null; then
    print_message "应用启动成功！"
    echo
    echo "=========================================="
    echo "部署完成！"
    echo "=========================================="
    echo "项目目录：$PROJECT_DIR"
    echo "数据库：$DB_NAME"
    echo "端口：8080"
    echo "API文档：http://localhost:8080/api/doc.html"
    echo "Swagger UI：http://localhost:8080/api/swagger-ui.html"
    echo "日志文件：$PROJECT_DIR/logs/"
    echo
    echo "默认管理员账号："
    echo "用户名：admin"
    echo "密码：123456"
    echo
    echo "请及时修改默认密码！"
    echo "=========================================="
else
    print_error "应用启动失败，请检查日志文件：$PROJECT_DIR/logs/startup.log"
    tail -n 20 "$PROJECT_DIR/logs/startup.log"
    exit 1
fi

# 步骤8：配置防火墙（可选）
echo -n "是否配置防火墙开放8080端口？(y/N): "
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
    if command -v ufw &> /dev/null; then
        ufw allow 8080
        print_message "防火墙已配置，开放8080端口"
    elif command -v firewall-cmd &> /dev/null; then
        firewall-cmd --permanent --add-port=8080/tcp
        firewall-cmd --reload
        print_message "防火墙已配置，开放8080端口"
    else
        print_warning "未找到防火墙管理工具，请手动开放8080端口"
    fi
fi

print_message "快速部署完成！"